package com.bbcare.followup.plat.controller;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bbcare.comm.AppException;
import com.bbcare.comm.Constants;
import com.bbcare.comm.DateUtil;
import com.bbcare.comm.ErrorCode;
import com.bbcare.comm.PropertiesUtils;
import com.bbcare.comm.QueryModel;
import com.bbcare.comm.ResultModel;
import com.bbcare.comm.SeqUtil;
import com.bbcare.comm.ToolUtils;
import com.bbcare.department.plat.entity.DepartmentBasic;
import com.bbcare.department.plat.entity.Doctor;
import com.bbcare.department.plat.service.IBsStaticParamService;
import com.bbcare.department.plat.service.IDepartmentBasicService;
import com.bbcare.department.plat.service.IDoctorManagerService;
import com.bbcare.followup.plat.entity.FollowQueue;
import com.bbcare.followup.plat.entity.Patient;
import com.bbcare.followup.plat.service.IFollowQueueService;
import com.bbcare.followup.plat.service.IPatientService;
import com.bbcare.followup.plat.service.IPatientqueryCardService;
import com.bbcare.followup.plat.service.IWeChatUserService;
import com.bbcare.followup.plat.store.ibatis.IConfCacheDAO;
import com.bbcare.plat.support.service.IBizInterAsClient;

/**
 * @desc 用户绑定卡信息控制类
 * @author wuyz
 *
 */
@Controller
@RequestMapping("/webapi/service/patient")
public class PatientqueryCardController {
	Logger logger = Logger.getLogger(PatientqueryCardController.class);

	@Autowired
	private IPatientqueryCardService patientqueryCardService;

	@Autowired
	private IPatientService patientSerivce;

	@Autowired
	private IDepartmentBasicService deparmentBasicService;

	@Autowired
	private IDoctorManagerService doctorManagerService;

	@Autowired
	private IBsStaticParamService bsStaticParamService;

	@Autowired
	private IFollowQueueService followQueueService;

	@Autowired
	private IBizInterAsClient bizInterClient;

	@Autowired
    private IWeChatUserService weChatUserService;

	@Autowired
    public IConfCacheDAO confCacheDao;


	/**
	 * 根据科室微信id查询用户是否绑定卡 (通过微信id查询患者id，然后通过患者id去查卡信息)
	 *
	 * @param jsonStr
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping("/querypatientcardinfo")
	public ResultModel<HashMap<String, Object>> getpatientCard(HttpServletRequest request, @RequestBody String jsonStr)
			throws Exception {
		logger.info("in PatientqueryCardController----arg==" + jsonStr);
		JSONObject jsonEsb = JSON.parseObject(jsonStr);
		JSONObject requestParam = jsonEsb.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD); // 统一节点处理
		// HashMap<String, Object>userMap =new HashMap<String,Object>();
		if (null == requestParam) {
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！");
		}

		/* channel渠道类型必传字段app登陆时特殊处理标识，跳过登陆 */
		String channel = requestParam.getString("channel");
		if (null == channel || !PropertiesUtils.getProperty("channel").equals(channel)) {
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "channel传入为空或者传入值不正确!");
		}

		String phoneNo = requestParam.getString("phoneNo");
		if (StringUtils.isEmpty(phoneNo)) {
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "缺少服务号码");
		}

		String userName = requestParam.getString("userName");
		if (StringUtils.isEmpty(userName)) {
			logger.warn("in 判断微信id是否传入----arg==" + jsonStr);
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "缺少用户姓名");
		}

		Map<String, Object> paramMap = new HashMap<String, Object>();
		String openid = requestParam.getString("openid");
		// 微信id用于查询患者id
		String code = requestParam.getString("code");// 微信code
		if (StringUtils.isEmpty(code) && StringUtils.isEmpty(openid)) {
			logger.warn("in 判断微信id是否传入----arg==" + jsonStr);
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "缺少微信ID");
		}
		if (StringUtils.isBlank(openid)) {
			openid = ToolUtils.getOpenId(code);
		}
		if(StringUtils.isBlank(openid)) {
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "缺少微信ID");
		}
		String queueId = requestParam.getString("queueId");
		if (StringUtils.isEmpty(queueId)) {
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "缺少队列或者科室id");
		}
		String tenantId = "";// 租户id
		if (!StringUtils.isBlank(queueId)) {
			Map<String, Object> Map = new HashMap<String, Object>();
			Map.put("id", queueId);
			FollowQueue queue = followQueueService.getQueueDetailByQueueId(Map);
			tenantId = queue.getTenantId();
		}

		String bookeddept = requestParam.getString("bookeddept");
		if(StringUtils.isBlank(bookeddept)) {
			bookeddept = "001";
		}
		logger.info("打印###openid###" + openid);
		paramMap.put("openId", openid);
		paramMap.put("tenantId", tenantId);
		paramMap.put("phoneNo", phoneNo);
		paramMap.put("userName", userName);
		paramMap.put("queueId", queueId);
		paramMap.put("bookeddept", bookeddept);
		// paramMap.put("userId", "olio_t8NVIlGJtPzAc_akn0x1Uuk");
		return patientqueryCardService.querypatientid(paramMap);
	}

	// 短信验证码
	@RequestMapping("/sendRegMsgAppUser")
	@ResponseBody
	public ResultModel<HashMap<String, Object>> sendRegMsgAppUser(HttpServletRequest request,
			@RequestBody String jsonStr) throws Exception {
		logger.info("in PatientqueryCardController----arg==" + jsonStr);
		JSONObject jsonEsb = JSON.parseObject(jsonStr);
		JSONObject requestParam = jsonEsb.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD); // 统一节点处理
		HashMap<String, Object> userMap = new HashMap<String, Object>();
		if (null == requestParam) {
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！");
		}
		/* channel渠道类型必传字段app登陆时特殊处理标识，跳过登陆 */
		String channel = requestParam.getString("channel");
		if (null == channel || !PropertiesUtils.getProperty("channel").equals(channel)) {
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "channel传入为空或者传入值不正确!");
		}
		String phoneNo = requestParam.getString("phoneNo");
		// String ip = request.getRemoteAddr();
		// 验证签名
		SortedMap<String, String> packageParams = new TreeMap<String, String>();
		// packageParams.put("key","bbcare.sms");
		packageParams.put("phoneNo", phoneNo);
		// packageParams.put("ip", ip);
		// packageParams.put("appType", appType);
		String content = requestParam.getString("content");
		String smsType = requestParam.getString("smsType");
		// 判断手机格式
		boolean re = ToolUtils.checkPhoneNo(phoneNo);
		if (re == false) {
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "手机号码格式不正确！");
		}
		userMap.put("code", "8888");
		// return new ResultModel<HashMap<String, Object>>(userMap);
		return patientqueryCardService.addsendPromptSms_tx(phoneNo, smsType, content);
	}

	// 短信验证码验证或者是证件验证
	@ResponseBody
	@RequestMapping("/checkVerifyCode")
	public ResultModel<HashMap<String, Object>> checkSmsVerifyCode(HttpServletRequest request,
			@RequestBody String jsonStr) throws Exception {
		logger.info("in checkSmsVerifyCode----arg==" + jsonStr);
		JSONObject jsonEsb = JSON.parseObject(jsonStr);
		JSONObject requestParam = jsonEsb.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD); // 统一节点处理
		HashMap<String, Object> userMap = new HashMap<String, Object>();
		if (null == requestParam) {
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！");
		}

		/* channel渠道类型必传字段app登陆时特殊处理标识，跳过登陆 */
		String channel = requestParam.getString("channel");
		if (null == channel || !PropertiesUtils.getProperty("channel").equals(channel)) {
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "channel传入为空或者传入值不正确!");
		}
		String phoneNo = requestParam.getString("phoneNo");
		if (StringUtils.isEmpty(phoneNo)) {
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "缺少服务号码ID");
		}
		String verifyCode = requestParam.getString("verifyCode");
		if (StringUtils.isEmpty(verifyCode)) {
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "缺少验证码");
		}
		String type = requestParam.getString("type");// 验证类型
		if (StringUtils.isEmpty(type)) {
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "缺少类型");
		}
		String smsType = requestParam.getString("smsType");// 短信类型
		if (StringUtils.isEmpty(smsType)) {
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "缺少短信类型");
		}
		if (StringUtils.isBlank(smsType)) {
			smsType = "01";
		}
		String wechat_id = requestParam.getString("wechat_id");
		if (StringUtils.isBlank(wechat_id)) {
			wechat_id = "";
		}

		int flag = patientqueryCardService.checkVerifyCode(phoneNo, verifyCode, smsType, type, wechat_id);
		if (flag == 1 && "1".equals(type)) {
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "尊敬的用户，您的验证码已经失效，请重新获取！");
		}
		// 安医大项目特殊处理，返回患者id和队列id
		String hospitalFlag = requestParam.getString("hospitalFlag");
		if (!StringUtils.isEmpty(hospitalFlag) && Constants.HOSPITAL_FOR_AYD_NAME.equals(hospitalFlag)) {
			String queueId = requestParam.getString("queueId");
			if (StringUtils.isEmpty(queueId)) {
				throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "队列id为空!");
			}
			Map<String, Object> qryUserIn = new HashMap<String, Object>();
			qryUserIn.put("phoneNo", phoneNo);
			qryUserIn.put("tenantId", Constants.PT_USER_INFO_DEFAULT_TENANT_ID);
			qryUserIn.put("queueId", queueId);
			qryUserIn.put("userStatus", Constants.PATIENT_QUEUESCHEME_USER_STATUS_NOMAL);
			qryUserIn.put("qryType", Constants.QRY_BASIC_USER_INFO_TYPE);
			List<Object> retList = patientSerivce.getPatientByPhoneNo(qryUserIn);
			if (CollectionUtils.isEmpty(retList)) {
				throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_PATIENT_QUEUE_NOT_EXIST, "队列下无此患者或已删除!");
			}
			Map<String, Object> qryUserOut = ToolUtils.typeCast(retList.get(0));
			userMap.put("queueId", queueId);
			userMap.put("patientId", qryUserOut.get("userId"));
			userMap.put("patientName", qryUserOut.get("userName"));
			userMap.put("birthday", qryUserOut.get("birthday"));
		}

		return new ResultModel<HashMap<String, Object>>(userMap);
	}

	// 根据号码查询 卡信息,绑定和解绑接口
	@ResponseBody
	@RequestMapping("/queryCommitcardinfo")
	public ResultModel<Map<String, Object>> querycardinfo(@RequestBody String arg) throws Exception {
		logger.warn("in querySynchData----arg==" + arg);
       // arg = "{\"data\":{\"channel\":\"BBCARE-APP\",\"is_bind\":\"no\",\"patName\":\"王佳琪\",\"pathash\":\"\",\"bookeddept\":\"002\",\"pattel\":\"13361816087\",\"platform_key\":\"14kEw30D0ED1SIIycWld\",\"queueId\":\"12chyyjlqueue001\"}}";
		JSONObject jsonArg = null;
		try {
			jsonArg = JSON.parseObject(arg);
		} catch (Exception ex) {
			ex.printStackTrace();
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR, "入参格式错误，非json格式！"));
		}
		JSONObject requestParam = jsonArg.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD); // 统一节点处理
		// String id = jsonArg.getString("id");
		String pattel = requestParam.getString("pattel");
		if (null == pattel || "".equals(pattel)) {
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，未传入服务号码或值为空！"));
		}
		String patName = requestParam.getString("patName");
		if (null == patName || "".equals(patName)) {
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，未传入患者姓名或值为空！"));
		}
		String is_bind = requestParam.getString("is_bind");
		if (null == is_bind || "".equals(is_bind)) {
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，未传入操作类型码或值为空！"));
		}
		String platform_key = requestParam.getString("platform_key");
		if (null == platform_key || "".equals(platform_key)) {
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，未传入患者id或值为空！"));
		}
		String pathash = requestParam.getString("pathash");
		if (!StringUtils.isBlank(is_bind) && is_bind.equals("unbind")) {
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "不支持解绑操作！"));
		} else {
			pathash = "";
		}

		String cardno = requestParam.getString("cardno");
		if (!StringUtils.isBlank(is_bind) && !is_bind.equals("no")) {
			if (null == cardno || "".equals(cardno)) {
				throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,
						"入参节点错误，未传入卡号或值为空！"));
			}
		} else {
			cardno = "";
		}

		String queueId = requestParam.getString("queueId");
		if (null == queueId || "".equals(queueId)) {
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，未传入队列id或值为空！"));
		}

		String bookeddept = requestParam.getString("bookeddept");
		if(StringUtils.isBlank(bookeddept)) {
			bookeddept = "001";
		}

		HashMap<String, Object> servParamMap = new LinkedHashMap<String, Object>();
		servParamMap.put("patName", patName);
		servParamMap.put("pattel", pattel);
		servParamMap.put("cardno", cardno);
		servParamMap.put("pathash", pathash);
		servParamMap.put("bookeddept", bookeddept);
		servParamMap.put("is_bind", is_bind);
		servParamMap.put("platform_code", Constants.SOURCE_TPLATFORM_CODE);
		servParamMap.put("platform_key", platform_key);
		servParamMap.put("queueId", queueId);
		// servParamMap.put("phoneNo", requestParam.getString("patname"));
		// System.out.println("servParamMap"+servParamMap.toString());
		List<Map<String, Object>> list = patientqueryCardService.getcardInfo(servParamMap);
		HashMap<String, Object> retMap = new HashMap<String, Object>();
		retMap.put("cardList", list);
		/*
		 * int total = 0; if (null != list) { total = list.size(); } retMap.put("rows",
		 * list); retMap.put("total", total);
		 */
		if (null != retMap && 0 != retMap.size()) {
			return new ResultModel<Map<String, Object>>(retMap);
		} else {
		}

		return new ResultModel<Map<String, Object>>(retMap);
	}

	// 创建新用户
	@ResponseBody
	@RequestMapping("/createNewUser")
	public ResultModel<Map<String, Object>> bindCardCommit(@RequestBody String arg) throws Exception {
		logger.warn("in querySynchData----arg==" + arg);
		// boolean flag = false;//是否需要新建患者
		JSONObject jsonArg = null;
		try {
			jsonArg = JSON.parseObject(arg);
		} catch (Exception ex) {
			ex.printStackTrace();
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR, "入参格式错误，非json格式！"));
		}
		JSONObject requestParam = jsonArg.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD); // 统一节点处理
		// String id = jsonArg.getString("id");
		String phoneNo = requestParam.getString("phoneNo");

		/* channel渠道类型必传字段app登陆时特殊处理标识，跳过登陆 */
		String channel = requestParam.getString("channel");
		if (null == channel || !PropertiesUtils.getProperty("channel").equals(channel)) {
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "channel传入为空或者传入值不正确!");
		}

		if (null == phoneNo || "".equals(phoneNo)) {
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，未传入服务号码或值为空！"));
		}
		HashMap<String, Object> servParamMap = new HashMap<String, Object>();
		// servParamMap.put("id", id);
		// 校验预产期是否传入
		Patient pt = new Patient();
		String birthday = requestParam.getString("birthday");
		String expectedDay = "";

		String createType = requestParam.getString("createType");
		if (StringUtils.isEmpty(createType)) {
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，用户类型为空！"));
		}
		int pregnancyDay = 0;
		if (!createType.equals(Constants.PATIENTTYPE_OTHER)) {
			if (StringUtils.isEmpty(birthday)) {
				throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，出生日期为空！"));
			}
			expectedDay = requestParam.getString("expectedDay");
			if (0 == pt.getPregnancyDay() && !StringUtils.isEmpty(expectedDay)) {
				// 根据生日和预产期计算孕周
				pregnancyDay = ToolUtils.calPrenDayByBirthAndExpect(birthday, expectedDay);
				pt.setPregnancyDay(pregnancyDay);
			} else {
				expectedDay = birthday;
				pregnancyDay = ToolUtils.calPrenDayByBirthAndExpect(birthday, birthday);
				pt.setPregnancyDay(pregnancyDay);
			}
		}

		String phoneNum = requestParam.getString("phoneNo");
		if (StringUtils.isEmpty(phoneNum)) {
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，服务号码为空！"));
		}
		String patientName = requestParam.getString("patientName");
		if (StringUtils.isEmpty(patientName)) {
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，患者姓名为空！"));
		}
		String queueId = requestParam.getString("followQueueId");
		if (StringUtils.isEmpty(queueId)) {
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，未传入队列id或值为空！"));
		}

		String deptId = requestParam.getString("deptId");
		if (StringUtils.isEmpty(deptId)) {
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，未传入科室id或值为空！"));
		}

		String gender = requestParam.getString("gender");
		if (StringUtils.isEmpty(gender)) {
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，性别为空！"));
		}

		String wechat_id = requestParam.getString("wechat_id");
		if (StringUtils.isEmpty(wechat_id)) {
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，微信id为空！"));
		}

		String card_status = requestParam.getString("card_status");
		/*
		 * if (StringUtils.isEmpty(card_status)) { throw (new AppException(ErrorCode.
		 * FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，未传入卡状态或值为空！")); }
		 */
		String card_type = requestParam.getString("card_type");
		/*
		 * if (StringUtils.isEmpty(card_type)) { throw (new AppException(ErrorCode.
		 * FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，卡类别为空！")); }
		 */

		String card_no = requestParam.getString("card_no");
		/*
		 * if (StringUtils.isEmpty(card_no)) { throw (new AppException(ErrorCode.
		 * FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，卡号为空！")); }
		 */
		String idCard = requestParam.getString("idIccid");
		/*if (StringUtils.isEmpty(idCard) || "undefided".equals(idCard)) {
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，证件信息不能为空！"));
		}*/

		String delivery = requestParam.getString("delivery");

		String tenantId = "";// 租户id
		if (!StringUtils.isBlank(queueId)) {
			Map<String, Object> Map = new HashMap<String, Object>();
			Map.put("id", queueId);
			FollowQueue queue = followQueueService.getQueueDetailByQueueId(Map);
			tenantId = queue.getTenantId();
		}
		// 来源渠道，入参若无，则默认扫码主诉渠道
        String sourceType = (String) servParamMap.get("sourceType");
        if (StringUtils.isBlank(sourceType)) {
            sourceType = Constants.PATIENT_SOURCE_TYPE_SCAN_SYMPTOM;// 扫码主诉渠道
        }
        servParamMap.put("sourceType", sourceType);

		Map<String, Object> userMap = new HashMap<String, Object>();
		HashMap<String, Object> listretMap = new HashMap<String, Object>();
		listretMap.put("queueId", queueId);
		listretMap.put("phoneNo", phoneNum);
		listretMap.put("userName", patientName);
		listretMap.put("wechat_id", wechat_id);
		listretMap.put("tenantId", tenantId);
		listretMap.put("birthday", birthday);
		listretMap.put("gender", gender);
		Map<String, Object> map = patientqueryCardService.getPatientinfoByphone(listretMap);
		boolean flag = (boolean) map.get("flag");
		String author = "app端";
		String authorName = requestParam.getString("patientName");// 由于是app端自主生成所以为患者名称
		String currTime = DateUtil.getTimeString(DateUtil.getSysDateA());// 创建时间
		String updateAccept = SeqUtil.getSeqNo(Constants.SEQ_NO_FOR_SYSTEMID);// 操作流水
		String userType = "";
		if (!flag) {
			if (StringUtils.isBlank(delivery) || !delivery.equals("0")) {
				// 创建人微信app自主填写
				userType = "";
				// 判断用户类型
				if (createType.equals(Constants.PATIENTTYPE_BABY)) {
					userType = "1";
					pt.setBirthday(birthday);
					pt.setExpectedDay(expectedDay);
					pt.setPregnancyDay(pregnancyDay);
				} else if (createType.equals(Constants.PATIENTTYPE_WOMEN)) {
					userType = "2";
					gender = "F";
					pt.setBirthday(birthday);
					pt.setExpectedDay(expectedDay);
				} else {
					userType = "3";
					SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 设置日期格式
					pt.setBirthday(birthday);
					pt.setExpectedDay(df.format(new Date()));
				}
				pt.setUserName(authorName);
				pt.setPhoneNo(phoneNum);
				pt.setFirstName(authorName.substring(0, 1));
				pt.setCreateTime(currTime);
				pt.setUpdateTime(currTime);
				pt.setCreateAuthor(author);
				pt.setGender(gender);
				pt.setUserType(userType);
				pt.setSourceType(sourceType);
				pt.setWechat_id(wechat_id);
				pt.setIdCard(idCard);

				servParamMap.put("patient", pt);
				servParamMap.put("authorName", authorName);
				servParamMap.put("queueId", queueId);
				servParamMap.put("updateTime", currTime);
				servParamMap.put("authorId", author);
				servParamMap.put("updateAccept", updateAccept);
				servParamMap.put("tenantId", tenantId);
				servParamMap.put("opCode", "1000");
				servParamMap.put("deptId", deptId);// 科室id
				// servParamMap.put("opNote", "患者自主创建患者信息");
				servParamMap.put("opType", "1");
				servParamMap.put("wechat_id", wechat_id);
				servParamMap.put("wechat_id", wechat_id);
				servParamMap.put("card_status", card_status);
				servParamMap.put("card_type", card_type);
				servParamMap.put("idCard", idCard);
				servParamMap.put("extendInfo", requestParam.getJSONObject("extendInfo"));// 问卷答案
				logger.info("3232323" + servParamMap.toString());
				userMap = patientSerivce.registerPatient(servParamMap);
				// patientqueryCardService.updateWechatId(listretMap);
				return new ResultModel<Map<String, Object>>(userMap);
			} else {
				List<Patient> listbaby = new ArrayList<Patient>();
				Patient baby = null;
				pt.setUserName(authorName);
				pt.setPhoneNo(phoneNo);
				pt.setFirstName(authorName.substring(0, 1));
				pt.setCreateTime(currTime);
				pt.setUpdateTime(currTime);
				pt.setBirthday(birthday);
				pt.setExpectedDay(expectedDay);
				pt.setPregnancyDay(pregnancyDay);
				pt.setGender(gender);
				pt.setWechat_id(wechat_id);
				pt.setIdCard(idCard);
				userType = "2";
				pt.setUserType(userType);
				pt.setSourceType(sourceType); // 扫码建档
				JSONArray babyInfo = requestParam.getJSONArray("babyInfo");
				// babyInfo = jsonData.getJSONObject("babyInfo");
				logger.info("babyInfo##############" + babyInfo);
				if (null != babyInfo) {
					//// System.out.println("babyInfo.size()@@@"+babyInfo.size());
					for (int i = 0; i < babyInfo.size(); i++) {
						baby = new Patient();
						baby = new Patient();
						JSONObject jo = (JSONObject) babyInfo.get(i);
						baby.setUserName(jo.getString("babyName"));
						baby.setPhoneNo(phoneNo);
						baby.setFirstName(jo.getString("babyName").substring(0, 1));
						baby.setCreateTime(currTime);
						baby.setUpdateTime(currTime);
						baby.setCreateAuthor("");
						baby.setBirthday(jo.getString("babyBirthday"));
						baby.setExpectedDay(expectedDay);
						baby.setPregnancyDay(pregnancyDay);
						baby.setGender(jo.getString("babyGender"));
						baby.setUserType("1");
						baby.setWechat_id(wechat_id);
						baby.setSourceType(sourceType); // 扫码建档
						baby.setIdCard(idCard);
						listbaby.add(i, baby);
					}
					// baby.setRelevantId(relevantId);
					servParamMap.put("patient", pt);
					servParamMap.put("listbaby", listbaby);
					if (listbaby == null || listbaby.size() <= 0) {
						servParamMap.put("patientBaby", baby);
					}
					servParamMap.put("defaultBabyQueueId", queueId);
					servParamMap.put("queueId", queueId);//

					servParamMap.put("updateTime", currTime);
					servParamMap.put("updateAccept", updateAccept);
					servParamMap.put("opCode", "1000");
					// servParamMap.put("opNote","患者通过二维码扫码进行建档操作");
					servParamMap.put("opType", "1");// 患者自助
					servParamMap.put("deptId", deptId);// 科室id
					servParamMap.put("wechat_id", wechat_id);
					servParamMap.put("card_status", card_status);
					servParamMap.put("card_type", card_type);
					servParamMap.put("card_no", card_no);
					servParamMap.put("idCard", idCard);
					userMap = patientSerivce.registerPatientForQrcode(servParamMap);

					return new ResultModel<Map<String, Object>>(userMap);
				} else {
					throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_DEPARTMENT_DEFAULT_QUEUE_NOT_EXIST,
							"该产妇已分娩，宝宝信息必须存在！"));
				}
			}
		} else {
			return new ResultModel<Map<String, Object>>(map);
		}
	}

	// 查询科室信息
	@ResponseBody
	@RequestMapping("/deptBasicInfoDetail")
	public ResultModel<DepartmentBasic> getDepartmentBasic(HttpServletRequest request, @RequestBody String jsonStr)
			throws Exception {
		logger.info("in getDepartmentBasic----arg==" + jsonStr);

		JSONObject jsonEsb = JSON.parseObject(jsonStr);
		JSONObject requestParam = jsonEsb.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD); // 统一节点处理
		if (null == requestParam) {
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！");
		}

		String tenantId = (String) requestParam.get("tenantId");// 科室id
		String queueId = (String) requestParam.get("queueId");// 租户id
		if (StringUtils.isEmpty(tenantId) && StringUtils.isEmpty(queueId)) {
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,
					"入参节点错误，科室id和队列id不能同时为空！");
		}

		if (!StringUtils.isBlank(queueId)) {
			Map<String, Object> Map = new HashMap<String, Object>();
			Map.put("id", queueId);
			FollowQueue queue = followQueueService.getQueueDetailByQueueId(Map);
			tenantId = queue.getDeptId();
		}
		logger.info("deptId####:" + tenantId + " queueId:" + queueId);

		DepartmentBasic departmentBasic = deparmentBasicService.getDepartmentBasicDetails(tenantId);
		logger.info("out getDepartmentBasic----arg==" + departmentBasic);
		return new ResultModel<DepartmentBasic>(departmentBasic);
	}

	// 查询科室医生信息
	@ResponseBody
	@RequestMapping("/listDocterinfo")
	public QueryModel<Doctor> listDocterinfo(HttpServletRequest request, @RequestBody String jsonStr) throws Exception {
		logger.info("in getDoctorlist----arg==" + jsonStr);
		JSONObject jsonEsb = JSON.parseObject(jsonStr);

		String requestStr = jsonEsb.getString(Constants.INF_INPUTPARAM_COMMONFIELD); // 统一节点处理
		JSONObject requestParam = null;
		if (!StringUtils.isEmpty(requestStr)) {
			requestParam = jsonEsb.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD); // 统一节点处理
		}
		Map<String, Object> paramMap = new HashMap<String, Object>();
		if (null != requestParam) {
			paramMap.putAll(requestParam);
		}

		String deptId = (String) requestParam.get("deptId");// 科室id
		String queueId = (String) requestParam.get("queueId");// 队列id
		if (StringUtils.isEmpty(deptId) && StringUtils.isEmpty(queueId)) {
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,
					"入参节点错误，科室id和队列id不能同时为空！");
		}

		String tenantId = (String) requestParam.get("tenantId");// 租户id
		if (StringUtils.isEmpty(tenantId)) {
			paramMap.put("tenantId", tenantId);
		}

		if (!StringUtils.isBlank(queueId)) {
			Map<String, Object> Map = new HashMap<String, Object>();
			Map.put("id", queueId);
			FollowQueue queue = followQueueService.getQueueDetailByQueueId(Map);
			deptId = queue.getDeptId();
		}
		logger.info("deptId####:" + deptId + " queueId:" + queueId);
		paramMap.put("deptId", deptId);

		List<Doctor> doctors = doctorManagerService.getDoctorsByCondition(paramMap);
		Map<String, Object> titleParam = new HashMap<String, Object>();
		titleParam.put("deptId", deptId);
		titleParam.put("type", Constants.DOCTOR_TITLE_TYPE_CODE);
		Map<String, String> titleMap = bsStaticParamService.getStaticParamsForMap(titleParam);
		logger.info("titleMap" + titleMap.toString());
		// 拼医生职称中文名字
		Doctor doctor = null;
		if (!CollectionUtils.isEmpty(doctors)) {
			for (int i = 0; i < doctors.size(); i++) {
				doctor = doctors.get(i);
				doctors.get(i).setDoctorTitleName(titleMap.get(doctor.getDoctorTitle()));
			}
		}

		Integer count = doctorManagerService.getDoctorCountByDeptId(paramMap);
		logger.info("out getDoctorlist----arg==" + doctors);
		return new QueryModel<Doctor>(doctors, count);
	}

	// 查询主诉登记模板
	@ResponseBody
	@RequestMapping("/queryJson")
	public ResultModel<Map<String, Object>> queryJson(HttpServletRequest request, @RequestBody String jsonStr)
			throws Exception {
		logger.info("in getPtContData----arg==" + jsonStr);
		JSONObject jsonEsb = JSON.parseObject(jsonStr);
		JSONObject requestParam = jsonEsb.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD); // 统一节点处理

		if (null == requestParam) {
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！");
		}

		String channel = requestParam.getString("channel");
		if (null == channel || !PropertiesUtils.getProperty("channel").equals(channel)) {
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "channel传入为空或者传入值不正确!");
		}

		String patientId = requestParam.getString("userId");
		if (StringUtils.isEmpty(patientId)) {
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参校验失败，患者不能为空!");
		}
		String queueId = requestParam.getString("queueId");
		String deptId = requestParam.getString("deptId");
		if (StringUtils.isEmpty(queueId) && StringUtils.isEmpty(deptId)) {
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,
					"入参校验失败，队列id和科室id不能同时为空!");
		}
		String type = requestParam.getString("type");
		if (StringUtils.isEmpty(type)) {
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参校验失败，问卷类型不能为空!");
		}

		// 根据deptId查询 默认队列信息 //宝宝 产妇
		String defaultQueueId = null; // 默认产妇队列
		String defaultBabyQueueId = null;// 默认宝宝队列
		String userType = requestParam.getString("userType");// 用户类型
		if (!StringUtils.isBlank(deptId)) {
			Map<String, Object> queueParam = new HashMap<String, Object>();
			queueParam.put("deptId", deptId);
			queueParam.put("defaultOption", Constants.DEPARTMENT_DEFAULT_QUEUE_STATUS);
			queueParam.put("queueStatus", Constants.QUEUE_STATUS_NOMAL);
			List<FollowQueue> queueList = followQueueService.getDefaultQueueByDeptId(queueParam);
			if (!CollectionUtils.isEmpty(queueList)) {
				for (int i = 0; i < queueList.size(); i++) {
					if (Constants.QUEUE_USER_TYPE_BABY.equals(queueList.get(i).getQueueUsertype())) {
						defaultBabyQueueId = queueList.get(i).getId();
					} else if (Constants.QUEUE_USER_TYPE_PARTURIENT.equals(queueList.get(i).getQueueUsertype())) {
						defaultQueueId = queueList.get(i).getId();
					}
				}
			}
			if (!StringUtils.isBlank(userType)) {
				if (userType.equals(Constants.QUEUE_USER_TYPE_BABY)) {
					queueId = defaultBabyQueueId;
				} else {
					queueId = defaultQueueId;
				}
			}
		}

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("patientId", patientId);
		map.put("invokeType", "1");// app调用
		map.put("queueId", queueId);
		map.put("type", type);
		logger.info("qqqqqqqqqqqqqqqqwww:" + map.toString());
		Map<String, Object> rspMap = patientqueryCardService.selectByIdALL(map);
		return new ResultModel<Map<String, Object>>(rspMap);
	}

	// 校验是否需要填写问卷
	@ResponseBody
	@RequestMapping("/checkCommit")
	public ResultModel<List<Map<String, Object>>> checkCommit(HttpServletRequest request, @RequestBody String jsonStr)
			throws Exception {
		logger.info("in getPtContData----arg==" + jsonStr);
		JSONObject jsonEsb = JSON.parseObject(jsonStr);
		JSONObject requestParam = jsonEsb.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD); // 统一节点处理

		if (null == requestParam) {
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！");
		}

		String channel = requestParam.getString("channel");
		if (null == channel || !PropertiesUtils.getProperty("channel").equals(channel)) {
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "channel传入为空或者传入值不正确!");
		}

		String patName = requestParam.getString("patName");
		if (StringUtils.isEmpty(patName)) {
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参校验失败，姓名不能为空!");
		}
		String pathash = requestParam.getString("pathash");

		if (StringUtils.isEmpty(pathash)) {
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参校验失败，病人识别码不能为空!");
		}
		String platform_key = requestParam.getString("platform_key");
		if (StringUtils.isEmpty(platform_key)) {
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参校验失败，患者id不能为空!");
		}

		HashMap<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("patName", patName);
		paramMap.put("pathash", pathash);
		paramMap.put("platform_code", Constants.SOURCE_TPLATFORM_CODE);
		paramMap.put("platform_key", platform_key);
		paramMap.put("code", Constants.STRING_SERVICECODE_A09U001O);
		String argmsg = bizInterClient.call(Constants.SERVICE_NAME_FOR_SERVICE, "", paramMap);
		//argmsg="<?xml version=\"1.0\" encoding=\"gbk\"?><rows><result><result_code>1</result_code><result_msg>可答卷</result_msg></result><detail><bookid>8870800</bookid></detail></rows>";
		logger.info("################" + argmsg);
		List<Map<String, Object>> list = ToolUtils.FormatXml(argmsg);
		logger.info(list.toString());
		if (list == null || list.size() <= 0) {
			list = null;
		}
		return new ResultModel<List<Map<String, Object>>>(list);
	}

	// 患者添加
	@ResponseBody
	@RequestMapping("/register/patientForQRCode")
	public ResultModel<Map<String, Object>> patientForQRCode(@RequestBody String arg, HttpServletRequest request)
			throws Exception {
		logger.warn("in patientForQRCode----arg==" + arg.toString());

		JSONObject jsonArg = null;
		try {
			jsonArg = JSON.parseObject(arg);
		} catch (Exception ex) {
			ex.printStackTrace();
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR, "入参格式错误，非json格式！"));
		}

		JSONObject jsonData = jsonArg.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD);
		if (null == jsonData) {
			// 前台必须传data节点，否则报错返回
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！"));
		}
		String currTime = DateUtil.getTimeString(DateUtil.getSysDateA());// 创建时间
		String updateAccept = SeqUtil.getSeqNo(Constants.SEQ_NO_FOR_SYSTEMID);// 操作流水

		// 参数校验后续补充
		String deptId = jsonData.getString("deptId");
		String queueId = jsonData.getString("queueId");
		if (StringUtils.isBlank(deptId) && StringUtils.isBlank(queueId)) {
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,
					"入参节点错误，科室id和队列不能同时为空！"));
		}

		String userType = jsonData.getString("userType");
		if (!StringUtils.isBlank(deptId) && StringUtils.isBlank(userType)) {
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，患者类型为空！"));
		}

		// 根据deptId查询 默认队列信息 //宝宝 产妇
		String defaultQueueId = null; // 默认产妇队列
		String defaultBabyQueueId = null;// 默认宝宝队列
		if (!StringUtils.isBlank(queueId)) {
			if (queueId.equals(Constants.GFY_ZHUSU_QUEUEWOMEN)) {
				userType = "1";
			} else if (queueId.equals(Constants.GFY_ZHUSU_QUEUEBABY)) {
				userType = "0";
			}
			Map<String, Object> Map = new HashMap<String, Object>();
			Map.put("id", queueId);
			FollowQueue queue = followQueueService.getQueueDetailByQueueId(Map);
			deptId = queue.getDeptId();
		}
		Map<String, Object> queueParam = new HashMap<String, Object>();
		queueParam.put("deptId", deptId);
		queueParam.put("defaultOption", Constants.DEPARTMENT_DEFAULT_QUEUE_STATUS);
		queueParam.put("queueStatus", Constants.QUEUE_STATUS_NOMAL);
		List<FollowQueue> queueList = followQueueService.getDefaultQueueByDeptId(queueParam);
		if (!CollectionUtils.isEmpty(queueList)) {
			for (int i = 0; i < queueList.size(); i++) {
				if (Constants.QUEUE_USER_TYPE_BABY.equals(queueList.get(i).getQueueUsertype())) {
					defaultBabyQueueId = queueList.get(i).getId();
				} else if (Constants.QUEUE_USER_TYPE_PARTURIENT.equals(queueList.get(i).getQueueUsertype())) {
					defaultQueueId = queueList.get(i).getId();
				}
			}
		}

		Map<String, Object> servParamMap = jsonData;

		String phoneNo = jsonData.getString("phoneNo");
		if (StringUtils.isBlank(phoneNo)) {
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，服务号码为空！"));
		}

		String userName = jsonData.getString("userName");
		if (StringUtils.isBlank(userName)) {
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，就诊人姓名为空！"));
		}
		// 来源渠道，入参若无，则默认扫码主诉渠道
        String sourceType = (String) servParamMap.get("sourceType");
        if (StringUtils.isBlank(sourceType)) {
            sourceType = Constants.PATIENT_SOURCE_TYPE_SCAN_SYMPTOM;// 扫码主诉渠道
        }
        servParamMap.put("sourceType", sourceType);

		/*
		 * String expectedDay = jsonData.getString("expectedDay"); if
		 * (StringUtils.isBlank(expectedDay)) { throw (new AppException(ErrorCode.
		 * FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,
		 * "入参节点错误，当为用户类型为宝宝时,预产期不能为空！")); }
		 */

		String openId = jsonData.getString("openId");
		// 校验预产期是否传入
		Patient pt = null; // 产妇
		Patient baby = null;
		List<Patient> listbaby = new ArrayList<Patient>();
		String gender = "";
		String birthday = "";
		String pregnancyWeek = ""; // 孕周

		String childbirth = "";
		JSONArray babyInfo = null;
		String babyGender = "";
		String babyBirthday = "";

		String expectedDay = "";
		birthday = jsonData.getString("birthday");
		gender = jsonData.getString("gender");
		expectedDay = jsonData.getString("expectedDay");
		if (userType.equals(Constants.QUEUE_USER_TYPE_BABY)) {
			userType="1";
			baby = new Patient();
			babyGender = jsonData.getString("gender");
			babyBirthday = jsonData.getString("birthday");
			expectedDay = jsonData.getString("expectedDay");
			pregnancyWeek = ToolUtils.calPrenDayByBirthAndExpect(birthday, expectedDay) + "";
			if (StringUtils.isBlank(babyBirthday)) {
				throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,
						"入参节点错误，当为用户类型为宝宝时,出生不能为空！"));
			}
			if (StringUtils.isBlank(babyGender)) {
				throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,
						"入参节点错误，当为用户类型为宝宝时,性别不能为空！"));
			}
			if (StringUtils.isBlank(pregnancyWeek)) {
				throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,
						"入参节点错误，当为用户类型为宝宝时,孕周不能为空！"));
			}

			if (StringUtils.isBlank(defaultBabyQueueId)) {
				throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_DEPARTMENT_DEFAULT_QUEUE_NOT_EXIST,
						"该科室没有配置宝宝默认队列信息"));
			}

			baby.setUserName(userName);
			baby.setPhoneNo(phoneNo);
			baby.setFirstName(userName.substring(0, 1));
			baby.setCreateTime(currTime);
			baby.setUpdateTime(currTime);
			baby.setCreateAuthor("");
			baby.setBirthday(babyBirthday);
			baby.setExpectedDay(expectedDay);
			baby.setPregnancyDay(Integer.parseInt(pregnancyWeek));
			baby.setGender(babyGender);
			baby.setUserType(userType);
			baby.setWechat_id(openId);
			baby.setSourceType(sourceType); // 扫码建档
			// 根据生日和预产期计算孕周
			/*
			 * int pregnancyDay = ToolUtils.calPrenDayByBirthAndExpect(birthday,
			 * expectedDay); pt.setPregnancyDay(pregnancyDay);
			 */

		} else if (userType.equals(Constants.QUEUE_USER_TYPE_PARTURIENT)) {
			userType="2";
			childbirth = jsonData.getString("childbirth");
			if (StringUtils.isBlank(childbirth)) {
				throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,
						"入参节点错误，当为用户类型为产妇时,是否分娩不能为空！"));
			}
			pt = new Patient();
			pt.setUserName(userName);
			pt.setPhoneNo(phoneNo);
			pt.setFirstName(userName.substring(0, 1));
			pt.setCreateTime(currTime);
			pt.setUpdateTime(currTime);
			pt.setBirthday(birthday);
			pt.setExpectedDay(expectedDay);
			pt.setGender(gender);
			pt.setUserType(userType);
			pt.setSourceType(sourceType); // 扫码建档
			pt.setWechat_id(openId);

			if (Constants.PARTURIENT_CHILDBIRTH_YES.equals(childbirth)) {// 已分娩
				babyInfo = jsonData.getJSONArray("babyInfo");
				JSONObject jsonOne = null;
				if (babyInfo != null) {
					jsonOne = (JSONObject) babyInfo.get(0);
				}
				pregnancyWeek = ToolUtils.calPrenDayByBirthAndExpect(jsonOne.getString("babyBirthday"), expectedDay)
						+ "";
				if (StringUtils.isBlank(pregnancyWeek)) {
					throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,
							"入参节点错误，当为用户类型为产妇且已分娩时，孕周不能为空"));
				}

				pt.setPregnancyDay(Integer.parseInt(pregnancyWeek));
				// babyInfo = jsonData.getJSONObject("babyInfo");
				logger.info("babyInfo##############" + babyInfo);
				if (null != babyInfo) {
					if (StringUtils.isBlank(defaultBabyQueueId)) {
						throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_DEPARTMENT_DEFAULT_QUEUE_NOT_EXIST,
								"该科室没有配置宝宝默认队列信息"));
					}

					if (StringUtils.isBlank(defaultQueueId)) {
						throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_DEPARTMENT_DEFAULT_QUEUE_NOT_EXIST,
								"该科室没有配置产妇默认队列信息"));
					}
					//// System.out.println("babyInfo.size()@@@"+babyInfo.size());
					for (int i = 0; i < babyInfo.size(); i++) {
						baby = new Patient();
						JSONObject jo = (JSONObject) babyInfo.get(i);
						baby.setUserName(jo.getString("babyName"));
						baby.setPhoneNo(phoneNo);
						baby.setFirstName(jo.getString("babyName").substring(0, 1));
						baby.setCreateTime(currTime);
						baby.setUpdateTime(currTime);
						baby.setCreateAuthor("");
						baby.setBirthday(jo.getString("babyBirthday"));
						baby.setExpectedDay(expectedDay);
						baby.setPregnancyDay(Integer.parseInt(pregnancyWeek));
						baby.setGender(jo.getString("babyGender"));
						baby.setUserType("0");
						baby.setWechat_id(openId);
						baby.setSourceType(sourceType); // 扫码建档
						listbaby.add(i, baby);
					}
					// baby.setRelevantId(relevantId);
				} else {
					throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_DEPARTMENT_DEFAULT_QUEUE_NOT_EXIST,
							"该产妇已分娩，宝宝信息必须存在！"));
				}
			} else {
				if (StringUtils.isBlank(defaultQueueId)) {
					throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_DEPARTMENT_DEFAULT_QUEUE_NOT_EXIST,
							"该科室没有配置产妇默认队列信息"));
				}
				expectedDay = jsonData.getString("expectedDay");
				if (StringUtils.isBlank(expectedDay)) {
					throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,
							"入参节点错误，当为用户类型为产妇且未分娩时，预产期不能为空"));
				}
				pt.setExpectedDay(expectedDay);
			}
		} else {
			//
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "用户类型值不正确"));
		}
		servParamMap.put("patient", pt);
		servParamMap.put("listbaby", listbaby);
		if (listbaby == null || listbaby.size() <= 0) {
			servParamMap.put("patientBaby", baby);
		}
		servParamMap.put("defaultBabyQueueId", defaultBabyQueueId);
		servParamMap.put("queueId", defaultQueueId);//

		servParamMap.put("updateTime", currTime);
		servParamMap.put("updateAccept", updateAccept);
		servParamMap.put("opCode", "1000");
		servParamMap.put("opNote", "患者通过二维码扫码进行建档操作");
		servParamMap.put("opType", "1");// 患者自助
		servParamMap.put("deptId", deptId);// 科室id
		servParamMap.put("wechat_id", openId);
		servParamMap.put("contentData", jsonData.getJSONObject("questiones"));// 问卷答案
		logger.info("servParamMap~~~info~~~" + servParamMap.toString());
		Map<String, Object> userMap = patientSerivce.registerPatientForQrcode(servParamMap);

		return new ResultModel<Map<String, Object>>(userMap);
	}

	// 某个队列建档问卷查询
	@ResponseBody
	@RequestMapping("/patientAppContent")
	public ResultModel<Map<String, Object>> qryPatientAddContent(@RequestBody String arg) throws Exception {
		logger.warn("in qryPatientAddContent----arg==" + arg);

		JSONObject jsonArg = null;
		try {
			jsonArg = JSON.parseObject(arg);
		} catch (Exception ex) {
			ex.printStackTrace();
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR, "入参格式错误，非json格式！"));
		}

		JSONObject jsonData = jsonArg.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD);
		if (null == jsonData) {
			// 前台必须传data节点，否则报错返回
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！"));
		}

		Map<String, Object> retMap = new HashMap<String, Object>();
		HashMap<String, Object> paramMap = new HashMap<String, Object>();
		String schemeId = jsonData.getString("followSchemeId");
		String queueId = jsonData.getString("followQueueId");
		String userType = jsonData.getString("userType");// 用户类型
		String defaultQueueId = null; // 默认产妇队列
		String defaultBabyQueueId = null;// 默认宝宝队列
		if (StringUtils.isBlank(queueId)) {
			// 根据deptId查询 默认队列信息 //宝宝 产妇
			String deptId = jsonData.getString("deptId");
			Map<String, Object> queueParam = new HashMap<String, Object>();
			queueParam.put("deptId", deptId);
			queueParam.put("defaultOption", Constants.DEPARTMENT_DEFAULT_QUEUE_STATUS);
			queueParam.put("queueStatus", Constants.QUEUE_STATUS_NOMAL);
			List<FollowQueue> queueList = followQueueService.getDefaultQueueByDeptId(queueParam);
			//// System.out.println("ssssssssssssssssssssssssssssssssssss"+queueList.toString());
			if (!CollectionUtils.isEmpty(queueList)) {
				for (int i = 0; i < queueList.size(); i++) {
					if (Constants.QUEUE_USER_TYPE_BABY.equals(queueList.get(i).getQueueUsertype())) {
						defaultBabyQueueId = queueList.get(i).getId();
					} else if (Constants.QUEUE_USER_TYPE_PARTURIENT.equals(queueList.get(i).getQueueUsertype())) {
						defaultQueueId = queueList.get(i).getId();
					}
				}
			}
			if (Constants.QUEUE_USER_TYPE_BABY.equals(userType)) {
				queueId = defaultBabyQueueId;
			} else {
				queueId = defaultQueueId;
			}
		}

		if (null == schemeId || "".equals(schemeId)) {
			Map<String, Object> Map = new HashMap<String, Object>();
			Map.put("id", queueId);
			FollowQueue queue = followQueueService.getQueueDetailByQueueId(Map);
			if (!StringUtils.isBlank(queue.getSchemeId())) {
				schemeId = queue.getSchemeId();
			} else {
				// 队列下无应用方案，直接返回
				return new ResultModel<Map<String, Object>>(retMap);
			}

		}

		paramMap.put("schemeId", schemeId);
		paramMap.put("queueId", queueId);

		retMap = followQueueService.qryQueueSchemePatientAddContent(paramMap);

		return new ResultModel<Map<String, Object>>(retMap);
	}

	/**
	 * @name:获取预约科室列表控制类
	 * @description:查询医院预约科室
	 * @author: wuyz
	 * @date: 2017年7月17日
	 * @version: 1.0
	 * @param hospital
	 *            String : 医院代码<br/>
	 *            platform_code String : 医院代码<br/>
	 *            platform_access String : 平台轮询授权码<br/>
	 * @return
	 *
	 **/
	@ResponseBody
	@RequestMapping("/orderHosptalDept")
	public ResultModel<List<Map<String, Object>>> orderHosptalDept(@RequestBody String arg) throws Exception {
		logger.warn("in queryHosptalDept----arg==" + arg);

		JSONObject jsonArg = null;
		try {
			jsonArg = JSON.parseObject(arg);
		} catch (Exception ex) {
			ex.printStackTrace();
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR, "入参格式错误，非json格式！"));
		}

		JSONObject jsonData = jsonArg.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD);
		if (null == jsonData) {
			// 前台必须传data节点，否则报错返回
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！"));
		}

		String hospital = jsonData.getString("hospital");
		if (StringUtils.isBlank(hospital)) {
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，医院代码为空！"));
		}

		Map<String, Object> retMap = new LinkedHashMap<String, Object>();
		Map<String, Object> MapIn = new LinkedHashMap<String, Object>();
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();

		retMap.put("hospital", hospital);
		logger.info("Constants.SOURCE_HOSPTAL_CODE /:" + Constants.SOURCE_HOSPTAL_CODE);
		logger.info("Constants.SOURCE_ACCESS_CODE /:" + Constants.SOURCE_ACCESS_CODE);
		retMap.put("platform_code", Constants.SOURCE_HOSPTAL_CODE);
		retMap.put("platform_access", Constants.SOURCE_ACCESS_CODE);

		list = patientqueryCardService.orderCommonInfo(retMap, MapIn, 0);

		return new ResultModel<List<Map<String, Object>>>(list);
	}

	/**
	 * @name:获取预约专家信息控制类
	 * @description:获取预约专家信息
	 * @author: wuyz
	 * @date: 2017年7月17日
	 * @version: 1.0
	 * @param hospital
	 *            String : 医院代码<br/>
	 *            platform_code String : 医院代码<br/>
	 *            dept_code String : 科室代码<br/>
	 *            platform_access String : 平台轮询授权码<br/>
	 * @return
	 *
	 **/
	@ResponseBody
	@RequestMapping("/orderProfessor")
	public ResultModel<List<Map<String, Object>>> orderProfessor(@RequestBody String arg) throws Exception {
		logger.warn("in queryHosptalDept----arg==" + arg);

		JSONObject jsonArg = null;
		try {
			jsonArg = JSON.parseObject(arg);
		} catch (Exception ex) {
			ex.printStackTrace();
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR, "入参格式错误，非json格式！"));
		}

		JSONObject jsonData = jsonArg.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD);
		if (null == jsonData) {
			// 前台必须传data节点，否则报错返回
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！"));
		}

		String hospital = jsonData.getString("hospital");
		if (StringUtils.isBlank(hospital)) {
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，医院代码为空！"));
		}

		String dept_code = jsonData.getString("dept_code");
		if (StringUtils.isBlank(dept_code)) {
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，科室代码为空！"));
		}

		// 为了排序使用LinkedHashMap
		Map<String, Object> retMap = new LinkedHashMap<String, Object>();
		Map<String, Object> MapIn = new LinkedHashMap<String, Object>();
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();

		retMap.put("hospital", hospital);
		retMap.put("dept_code", dept_code);
		retMap.put("platform_code", Constants.SOURCE_HOSPTAL_CODE);
		retMap.put("platform_access", Constants.SOURCE_ACCESS_CODE);

		list = patientqueryCardService.orderCommonInfo(retMap, MapIn, 1);

		return new ResultModel<List<Map<String, Object>>>(list);
	}

	/**
	 * @name:获取预约资源模板控制类
	 * @description:获取预约资源模板
	 * @author: wuyz
	 * @date: 2017年7月17日
	 * @version: 1.0
	 * @param hospital
	 *            String : 医院代码<br/>
	 *            stdate String : 查询日期始(YYYY-MM-DD)<br/>
	 *            endate String : 查询日期止(YYYY-MM-DD)<br/>
	 *            dept_code String : 科室代码<br/>
	 *            expert_code String : 专家代码<br/>
	 *            partcode String : 项目类别代码<br/>
	 *            patfrom String : 病人来源<br/>
	 *            cancelled String : 是否停诊(TRUE / FALSE)<br/>
	 *            pregnancyDays String : 末次月经日期（约产科建卡必填,其他预约该字段可去除）<br/>
	 *            flag String : 1：完整版<br/>
	 *            platform_code String : 平台代码 11<br/>
	 *            platform_access String : 平台轮询授权码<br/>
	 * @return
	 *
	 **/
	@ResponseBody
	@RequestMapping("/orderResource")
	public ResultModel<List<Map<String, Object>>> orderResource(@RequestBody String arg) throws Exception {
		logger.warn("in queryHosptalDept----arg==" + arg);

		JSONObject jsonArg = null;
		try {
			jsonArg = JSON.parseObject(arg);
		} catch (Exception ex) {
			ex.printStackTrace();
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR, "入参格式错误，非json格式！"));
		}

		JSONObject jsonData = jsonArg.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD);
		if (null == jsonData) {
			// 前台必须传data节点，否则报错返回
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！"));
		}

		String hospital = jsonData.getString("hospital");
		if (StringUtils.isBlank(hospital)) {
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，科室代码为空！"));
		}

		String stdate = jsonData.getString("stdate");
		if (StringUtils.isBlank(stdate)) {
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，开始时间为空！"));
		}

		String endate = jsonData.getString("endate");
		if (StringUtils.isBlank(endate)) {
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，截止时间为空！"));
		}

		String dept_code = jsonData.getString("dept_code");
		if (StringUtils.isBlank(hospital)) {
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，科室代码为空！"));
		}

		String patfrom = jsonData.getString("patfrom");
		if (StringUtils.isBlank(patfrom)) {
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，病人来源为空！"));
		}

		String cancelled = jsonData.getString("cancelled");
		if (StringUtils.isBlank(cancelled)) {
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，是否停诊标识为空！"));
		}

		String flag = jsonData.getString("flag");
		if (StringUtils.isBlank(flag)) {
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，查询模板类型为空！"));
		}

		String expert_code = jsonData.getString("expert_code");
		if (StringUtils.isBlank(expert_code)) {
			expert_code = "";
		}

		String partcode = jsonData.getString("partcode");
		if (StringUtils.isBlank(partcode)) {
			partcode = "";
		}

		// 为了排序使用LinkedHashMap
		Map<String, Object> retMap = new LinkedHashMap<String, Object>();
		Map<String, Object> MapIn = new LinkedHashMap<String, Object>();

		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		retMap.put("hospital", hospital);
		retMap.put("stdate", stdate);
		retMap.put("endate", endate);
		retMap.put("dept_code", dept_code);
		retMap.put("expert_code", expert_code);
		retMap.put("partcode", partcode);
		retMap.put("patfrom", patfrom);
		retMap.put("cancelled", cancelled);
		retMap.put("flag", flag);
		retMap.put("platform_code", Constants.SOURCE_HOSPTAL_CODE);
		if (flag.equals("0")) {
			// 精简版
			retMap.put("platform_access", Constants.SOURCE_ACCESS_CODE);
		} else if (flag.equals("1")) {
			// 完整版
			String platform_key = jsonData.getString("platform_key");
			if (StringUtils.isBlank(platform_key)) {
				throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，用户id为空！"));
			}
			retMap.put("platform_key", platform_key);
			String deptl2code = jsonData.getString("deptl2code");
			if (!StringUtils.isBlank(deptl2code)) {
				retMap.put("dept_code", deptl2code);
			}
			String doctorid = jsonData.getString("doctorid");
			if (!StringUtils.isBlank(doctorid)) {
				retMap.put("expert_code", doctorid);
			}
			if (StringUtils.isBlank(partcode) && StringUtils.isBlank(doctorid)) {
				throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,
						"入参节点错误，项目类别代码和专家代码不能同时为空 ！"));
			}

		}
		list = patientqueryCardService.orderCommonInfo(retMap, MapIn, 2);

		return new ResultModel<List<Map<String, Object>>>(list);

	}

	/**
	 * @name:提交预约控制类
	 * @description:提交预约
	 * @author: wuyz
	 * @date: 2017年7月17日
	 * @version: 1.0
	 * @param hospital
	 *            String : 医院代码<br/>
	 *            templateid String : 预约模板Id<br/>
	 *            name String : 患者姓名<br/>
	 *            pattel String : 手机号码(TRUE / FALSE)<br/>
	 *            patfrom String : 预约来源（约产科建卡必填,其他预约该字段可去除）<br/>
	 *            webuserid String : 社区医院操作者工号<br/>
	 *            LMP String : 末次月经 预约产科建卡必填，其他预约该字段可去除<br/>
	 *            platform_code String : 平台代码 11<br/>
	 *            platform_access String : 平台轮询授权码<br/>
	 * @return map
	 *
	 **/
	@ResponseBody
	@RequestMapping("/orderCommit")
	public ResultModel<List<Map<String, Object>>> orderCommit(@RequestBody String arg) throws Exception {
		logger.warn("in queryHosptalDept----arg==" + arg);

		JSONObject jsonArg = null;
		try {
			jsonArg = JSON.parseObject(arg);
		} catch (Exception ex) {
			ex.printStackTrace();
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR, "入参格式错误，非json格式！"));
		}

		JSONObject jsonData = jsonArg.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD);
		if (null == jsonData) {
			// 前台必须传data节点，否则报错返回
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！"));
		}

		String hospital = jsonData.getString("hospital");
		if (StringUtils.isBlank(hospital)) {
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，科室代码为空！"));
		}

		String templateid = jsonData.getString("templateid");
		if (StringUtils.isBlank(templateid)) {
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，预约模板Id为空！"));
		}

		String name = jsonData.getString("name");
		if (StringUtils.isBlank(name)) {
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，患者姓名为空！"));
		}

		String patfrom = jsonData.getString("patfrom");
		if (StringUtils.isBlank(patfrom)) {
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，预约来源为空！"));
		}

		String webuserid = jsonData.getString("webuserid");
		if (StringUtils.isBlank(webuserid)) {
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，社区医院操作者工号为空！"));
		}

		String userId = jsonData.getString("userId");
		if (StringUtils.isBlank(userId)) {
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，用户id为空！"));
		}

		String queueId = jsonData.getString("queueId");
		if (StringUtils.isBlank(queueId)) {
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，队列id为空！"));
		}

		String ptSchemeId = jsonData.getString("ptSchemeId");
		if (StringUtils.isBlank(ptSchemeId)) {
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，方案id为空！"));
		}

		String platform_key = jsonData.getString("platform_key");
		if (StringUtils.isBlank(platform_key)) {
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，用户id为空！"));
		}

		String endtime = jsonData.getString("timeend");
		if (StringUtils.isBlank(endtime)) {
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，结束时间为空！"));
		}

		// 为了排序使用LinkedHashMap
		Map<String, Object> retMap = new LinkedHashMap<String, Object>();
		Map<String, Object> MapIn = new LinkedHashMap<String, Object>();
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();

		retMap.put("hospital", hospital);
		retMap.put("templateid", templateid);
		retMap.put("name", name);
		retMap.put("patfrom", patfrom);
		retMap.put("webuserid", webuserid);
		retMap.put("platform_code", Constants.SOURCE_HOSPTAL_CODE);
		retMap.put("platform_key", platform_key);

		MapIn.put("userId", userId);
		MapIn.put("queueId", queueId);
		MapIn.put("SchemeId", ptSchemeId);
		MapIn.put("date", jsonData.getString("date"));
		if (StringUtils.isBlank(endtime)) {
			endtime = "";
		}
		MapIn.put("endtime", endtime);

		list = patientqueryCardService.orderCommonInfo(retMap, MapIn, 3);

		return new ResultModel<List<Map<String, Object>>>(list);
	}

	/**
	 * @name:取消预约控制类
	 * @description:取消预约
	 * @author: wuyz
	 * @date: 2017年7月17日
	 * @version: 1.0
	 * @param hospital
	 *            String : 医院代码<br/>
	 *            platform_code String : 医院代码<br/>
	 *            reservationid String : 医院预约流水号<br/>
	 *            patfrom String : 病人来源<br/>
	 *            platform_access String : 平台轮询授权码<br/>
	 * @return
	 *
	 **/
	@ResponseBody
	@RequestMapping("/orderConcel")
	public ResultModel<List<Map<String, Object>>> orderConcel(@RequestBody String arg) throws Exception {
		logger.warn("in queryHosptalDept----arg==" + arg);

		JSONObject jsonArg = null;
		try {
			jsonArg = JSON.parseObject(arg);
		} catch (Exception ex) {
			ex.printStackTrace();
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR, "入参格式错误，非json格式！"));
		}

		JSONObject jsonData = jsonArg.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD);
		if (null == jsonData) {
			// 前台必须传data节点，否则报错返回
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！"));
		}

		String hospital = jsonData.getString("hospital");
		if (StringUtils.isBlank(hospital)) {
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，科室代码为空！"));
		}

		String patfrom = jsonData.getString("patfrom");
		if (StringUtils.isBlank(patfrom)) {
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，预约来源为空！"));
		}

		String reservationid = jsonData.getString("reservationid");
		if (StringUtils.isBlank(reservationid)) {
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，流水为空！"));
		}

		String platform_key = jsonData.getString("platform_key");
		if (StringUtils.isBlank(platform_key)) {
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，用户id为空！"));
		}

		String queueId = jsonData.getString("queueId");
		if (StringUtils.isBlank(queueId)) {
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，队列id为空！"));
		}

		String ptSchemeId = jsonData.getString("ptSchemeId");
		if (StringUtils.isBlank(ptSchemeId)) {
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，方案id为空！"));
		}
		// 为了排序使用LinkedHashMap
		Map<String, Object> retMap = new LinkedHashMap<String, Object>();
		Map<String, Object> MapIn = new LinkedHashMap<String, Object>();
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();

		retMap.put("hospital", hospital);
		retMap.put("reservationid", reservationid);
		retMap.put("patfrom", patfrom);
		retMap.put("platform_code", Constants.SOURCE_HOSPTAL_CODE);
		retMap.put("platform_key", platform_key);

		MapIn.put("queueId", queueId);
		MapIn.put("userStatus", "1");
		MapIn.put("SchemeId", ptSchemeId);
		MapIn.put("platform_key", platform_key);

		list = patientqueryCardService.orderCommonInfo(retMap, MapIn, 4);

		return new ResultModel<List<Map<String, Object>>>(list);
	}

	/**
	 * @name:修改随访时间和控制当前随访为已完成控制类
	 * @description:修改随访时间和控制当前随访为已完成
	 * @author: wuyz
	 * @date: 2017年7月20日
	 * @version: 1.0
	 * @param taskId
	 *            String：任务实例id userId String：用户id followQueueId String：队列id
	 *            finishDate String :完成时间 2017-07-21 ChangeDate : String 修改时间
	 *            2017-07-21 opType String :操作类型 01：更新随访状态；02：更新随访时间
	 * @return success boolean：true/flase
	 *
	 **/
	@ResponseBody
	@RequestMapping("/modTaskUpdate")
	public ResultModel<Map<String, Object>> modTaskUpdate(@RequestBody String arg) throws Exception {
		logger.warn("in modTaskUpdate----arg==" + arg);

		JSONObject jsonArg = null;
		try {
			jsonArg = JSON.parseObject(arg);
		} catch (Exception ex) {
			ex.printStackTrace();
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR, "入参格式错误，非json格式！"));
		}

		JSONObject jsonData = jsonArg.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD);
		if (null == jsonData) {
			// 前台必须传data节点，否则报错返回
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！"));
		}

		/* channel渠道类型必传字段app登陆时特殊处理标识，跳过登陆 */
		String channel = jsonData.getString("channel");
		if (null == channel || !PropertiesUtils.getProperty("channel").equals(channel)) {
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "channel传入为空或者传入值不正确!");
		}

		String taskId = jsonData.getString("taskId");
		if (null == taskId || "".equals(taskId)) {
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，未传入任务id或值为空！"));
		}

		String opType = jsonData.getString("opType");
		if (null == taskId || "".equals(taskId)) {
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，未传入类型或值为空！"));
		}

		String userId = jsonData.getString("userId");
		if (null == userId || "".equals(userId)) {
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，未传入用户id或值为空！"));
		}

		String followQueueId = jsonData.getString("followQueueId");
		if (null == followQueueId || "".equals(followQueueId)) {
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，未传入队列或值为空！"));
		}

		String updateTime = DateUtil.getTimeString(DateUtil.getSysDateA());// 创建时间
		String updateAccept = SeqUtil.getSeqNo(Constants.SEQ_NO_FOR_SYSTEMID);// 操作流水
		// 定义入参
		HashMap<String, Object> servParamMap = new HashMap<String, Object>();

		String finishDate = "";
		String ChangeDate = "";
		if (opType.equals(Constants.STRING_UPDATE_STAYUS)) {
			finishDate = jsonData.getString("finishDate");
			if (null == finishDate || "".equals(finishDate)) {
				throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,
						"入参节点错误，未传入完成时间或值为空！"));
			}
			servParamMap.put("finishDate", finishDate);
		} else if (opType.equals(Constants.STRING_UPDATE_EXECUTE)) {
			ChangeDate = jsonData.getString("ChangeDate");
			if (null == ChangeDate || "".equals(ChangeDate)) {
				throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,
						"入参节点错误，未传入修改的时间或值为空！"));
			}
			servParamMap.put("ChangeDate", ChangeDate);
		}

		servParamMap.put("userId", userId);
		servParamMap.put("taskId", taskId);
		servParamMap.put("followQueueId", followQueueId);
		servParamMap.put("opType", opType);
		servParamMap.put("updateTime", updateTime);
		servParamMap.put("updateAccept", updateAccept);

		// 出参
		Map<String, Object> retMap = new HashMap<String, Object>();

		// 调用业务逻辑层
		retMap = patientqueryCardService.UpdateTaskInfo(servParamMap);
		return new ResultModel<Map<String, Object>>(retMap);
	}

	/**
	 * 根据科室微信id查询当前用户绑定了多少
	 *
	 * @param jsonStr
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping("/getAllpatientList")
	public ResultModel<Map<String, Object>> getAllpatientList(HttpServletRequest request, @RequestBody String jsonStr)
			throws Exception {
		logger.info("in getAllpatientList----arg==" + jsonStr);
		JSONObject jsonEsb = JSON.parseObject(jsonStr);
		JSONObject requestParam = jsonEsb.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD); // 统一节点处理
		// HashMap<String, Object>userMap =new HashMap<String,Object>();
		if (null == requestParam) {
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！");
		}

		/* channel渠道类型必传字段app登陆时特殊处理标识，跳过登陆 */
		String channel = requestParam.getString("channel");
		if (null == channel || !PropertiesUtils.getProperty("channel").equals(channel)) {
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "channel传入为空或者传入值不正确!");
		}
		String phoneNo = requestParam.getString("phoneNo");// 用户号码
		/* 微信id用于查询患者id */
		String code = requestParam.getString("code");// 微信code
		String openid = requestParam.getString("openid");
		Map<String, Object> paramMap = new HashMap<String, Object>();
		if (StringUtils.isBlank(phoneNo)) {
			if (StringUtils.isEmpty(code) && StringUtils.isEmpty(openid)) {
				logger.warn("in 判断微信id是否传入----arg==" + jsonStr);
				throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "缺少微信ID");
			}
			if (StringUtils.isBlank(openid)||"null".equals(openid)) {
				openid = ToolUtils.getOpenId(code);
			}
		} else {
			openid = "";
			paramMap.put("phoneNo", phoneNo);
		}
		String queueId = requestParam.getString("queueId");
		if (StringUtils.isEmpty(queueId)) {
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "缺少队列或者科室id");
		}
		String tenantId = "";// 租户id
		if (!StringUtils.isBlank(queueId)) {
			Map<String, Object> Map = new HashMap<String, Object>();
			Map.put("id", queueId);
			FollowQueue queue = followQueueService.getQueueDetailByQueueId(Map);
			tenantId = queue.getTenantId();
		}
		logger.info("打印###openid###" + openid);

		if ((StringUtils.isEmpty(openid)||"null".equals(openid))&&StringUtils.isBlank(phoneNo)) {
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,
					"未获取到微信唯一标识，请重新扫码，给您带来不便，望请见谅！谢谢！");
		}

		paramMap.put("openId", openid);
		paramMap.put("tenantId", tenantId);
		paramMap.put("queueId", queueId);
		// paramMap.put("userId", "olio_t8NVIlGJtPzAc_akn0x1Uuk");
		Map<String,Object> map = new HashMap<String,Object>();
		map = patientqueryCardService.queryAllpatientList(paramMap);
		return new ResultModel<Map<String, Object>>(map);
	}



	/**
	 * 根据科室微信id修改用户号码
	 *
	 * @param jsonStr
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping("/ModifyUserPhoneNo")
	public ResultModel<Map<String, Object>> ModifyUserPhoneNo(HttpServletRequest request, @RequestBody String jsonStr)
			throws Exception {
		logger.info("in ModifyUserPhoneNo----arg==" + jsonStr);
		JSONObject jsonEsb = JSON.parseObject(jsonStr);
		JSONObject requestParam = jsonEsb.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD); // 统一节点处理
		// HashMap<String, Object>userMap =new HashMap<String,Object>();
		if (null == requestParam) {
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！");
		}

		/* channel渠道类型必传字段app登陆时特殊处理标识，跳过登陆 */
		String channel = requestParam.getString("channel");
		if (null == channel || !PropertiesUtils.getProperty("channel").equals(channel)) {
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "channel传入为空或者传入值不正确!");
		}
		String phoneNo = requestParam.getString("phoneNo");// 用户号码
		if (StringUtils.isEmpty(phoneNo)) {
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "缺少用户号码");
		}

		String oldPhoneNo = requestParam.getString("oldPhoneNo");// 用户号码
		if (StringUtils.isEmpty(phoneNo)) {
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "缺少原用户号码");
		}

		/* 微信id用于查询患者id */
		String code = requestParam.getString("code");// 微信code
		String openid = requestParam.getString("openid");
		Map<String, Object> paramMap = new HashMap<String, Object>();

		if (StringUtils.isEmpty(code) && StringUtils.isEmpty(openid)) {
			logger.warn("in 判断微信id是否传入--- -arg==" + jsonStr);
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "缺少微信ID");
		}
		if (StringUtils.isBlank(openid)) {
			openid = ToolUtils.getOpenId(code);
		}

		String queueId = requestParam.getString("queueId");
		if (StringUtils.isEmpty(queueId)) {
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "缺少队列或者科室id");
		}
		String tenantId = "";// 租户id
		String departId = "";// 科室id
		String smsFlag ="";//是否发送短信
		if (!StringUtils.isBlank(queueId)) {
			Map<String, Object> Map = new HashMap<String, Object>();
			Map.put("id", queueId);
			FollowQueue queue = followQueueService.getQueueDetailByQueueId(Map);
			tenantId = queue.getTenantId();
			departId = queue.getDeptId();
			smsFlag =  queue.getSmsFlag();
		}
		logger.info("打印###openid###" + openid);

		if (StringUtils.isEmpty(openid)) {
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,
					"未获取到微信唯一标识，请重新扫码，给您带来不便，望请见谅！谢谢！");
		}

		paramMap.put("openId", openid);
		paramMap.put("tenantId", tenantId);
		paramMap.put("queueId", queueId);
		paramMap.put("deptId", departId);
		paramMap.put("phoneNo", phoneNo);
		paramMap.put("oldPhoneNo", oldPhoneNo);
		paramMap.put("smsFlag", smsFlag);

		// paramMap.put("userId", "olio_t8NVIlGJtPzAc_akn0x1Uuk");
		Map<String,Object> map = new HashMap<String,Object>();
		map = patientqueryCardService.ModifyUserPhoneNo(paramMap);
		return new ResultModel<Map<String, Object>>(map);
	}

	// 获取儿保门诊推送事项患者清单
	@ResponseBody
	@RequestMapping("/PushPatients")
	public ResultModel<Object> PushPatients(@RequestBody String arg) throws Exception {
		logger.warn("in PushPatients----arg==" + arg);

		JSONObject jsonArg = null;
		try {
			jsonArg = JSON.parseObject(arg);
		} catch (Exception ex) {
			ex.printStackTrace();
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR, "入参格式错误，非json格式！"));
		}

		JSONObject jsonData = jsonArg.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD);
		if (null == jsonData) {
			// 前台必须传data节点，否则报错返回
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！"));
		}

		// channel渠道类型必传字段app登陆时特殊处理标识，跳过登陆
		String channel = jsonData.getString("channel");
		if (null == channel || !PropertiesUtils.getProperty("channel").equals(channel)) {
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "channel传入为空或者传入值不正确!");
		}

		// 为了排序使用LinkedHashMap
		Map<String, Object> retMap = new LinkedHashMap<String, Object>();
		Map<String, Object> MapIn = new LinkedHashMap<String, Object>();

		Object list = new ArrayList<Map<String, Object>>();

		retMap.put("puchcode", Constants.SOURCE_ACCESS_PUCHCODE);
		retMap.put("platform_code", Constants.SOURCE_HOSPTAL_CODE);
		retMap.put("platform_access", Constants.SOURCE_ACCESS_CODE);
		retMap.put("code", Constants.STRING_SERVICECODE_A09U004O);
		list = patientqueryCardService.pushCommonInfo(retMap, MapIn, 1);

		return new ResultModel<Object>(list);

	}

	// 获取儿保门诊指导意见详情
	@ResponseBody
	@RequestMapping("/GfyInterface/GetInstruction")
	public ResultModel<Object> GetInstruction(@RequestBody String arg) throws Exception {
		logger.warn("in GetInstruction----arg==" + arg);

		JSONObject jsonArg = null;
		try {
			jsonArg = JSON.parseObject(arg);
		} catch (Exception ex) {
			ex.printStackTrace();
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR, "入参格式错误，非json格式！"));
		}

		JSONObject jsonData = jsonArg.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD);
		if (null == jsonData) {
			// 前台必须传data节点，否则报错返回
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！"));
		}

		// channel渠道类型必传字段app登陆时特殊处理标识，跳过登陆
		String channel = jsonData.getString("channel");
		if (null == channel || !PropertiesUtils.getProperty("channel").equals(channel)) {
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "channel传入为空或者传入值不正确!");
		}

		String platform_key = jsonData.getString("platform_key");
		if (StringUtils.isBlank(platform_key)) {
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "未传入用户id或者值为!");
		}
		// 为了排序使用LinkedHashMap
		Map<String, Object> retMap = new LinkedHashMap<String, Object>();
		Map<String, Object> MapIn = new LinkedHashMap<String, Object>();

		Object list = new ArrayList<Map<String, Object>>();

		retMap.put("platform_key", platform_key);
		retMap.put("platform_code", Constants.SOURCE_HOSPTAL_CODE);
		list = patientqueryCardService.pushCommonInfo(retMap, MapIn, 2);

		return new ResultModel<Object>(list);

	}

	// 获取儿保门诊指导意见列表
	@ResponseBody
	@RequestMapping("/GfyInterface/GetInstructionInfomation")
	public ResultModel<Object> GetInstructionInfomation(@RequestBody String arg) throws Exception {
		logger.warn("in GetInstructionInfomation----arg==" + arg);

		JSONObject jsonArg = null;
		try {
			jsonArg = JSON.parseObject(arg);
		} catch (Exception ex) {
			ex.printStackTrace();
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR, "入参格式错误，非json格式！"));
		}

		JSONObject jsonData = jsonArg.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD);
		if (null == jsonData) {
			// 前台必须传data节点，否则报错返回
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！"));
		}

		// channel渠道类型必传字段app登陆时特殊处理标识，跳过登陆
		String channel = jsonData.getString("channel");
		if (null == channel || !PropertiesUtils.getProperty("channel").equals(channel)) {
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "channel传入为空或者传入值不正确!");
		}

		//用户id
		String platform_key = jsonData.getString("platform_key");
		if (StringUtils.isBlank(platform_key)) {
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "未传入用户id或者值为空!");
		}
		//指导意见id
		String yjid = jsonData.getString("yjid");
		if (StringUtils.isBlank(yjid)) {
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "未传入指导意见id或者值为空!");
		}
		// 为了排序使用LinkedHashMap
		Map<String, Object> retMap = new LinkedHashMap<String, Object>();
		Map<String, Object> MapIn = new LinkedHashMap<String, Object>();

		Object list = new ArrayList<Map<String, Object>>();

		retMap.put("platform_key", platform_key);
		retMap.put("platform_code", Constants.SOURCE_HOSPTAL_CODE);
		retMap.put("yjid", yjid);

		list = patientqueryCardService.pushCommonInfo(retMap, MapIn, 3);

		return new ResultModel<Object>(list);

	}

	/**
	 * 微信月度评估提交服务
	 *
	 * @time 2017-06-19
	 * @author wuyz
	 *
	 **/
	@ResponseBody
	@RequestMapping("/WeChatCommit")
	public ResultModel<Map<String, Object>> WeChatCommit(@RequestBody String arg) throws Exception {
		logger.warn("in WeChatCommit----arg==" + arg.toString());

		JSONObject jsonArg = null;
		try {
			jsonArg = JSON.parseObject(arg);
		} catch (Exception ex) {
			ex.printStackTrace();
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR, "入参格式错误，非json格式！"));
		}

		JSONObject jsonData = jsonArg.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD);
		if (null == jsonData) {
			// 前台必须传data节点，否则报错返回
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！"));
		}
		String currTime = DateUtil.getTimeString(DateUtil.getSysDateA());// 创建时间
		String updateAccept = SeqUtil.getSeqNo(Constants.SEQ_NO_FOR_SYSTEMID);// 操作流水

		// 参数校验后续补充
		String queueId = jsonData.getString("followQueueId");
		if(StringUtils.isEmpty(queueId)){
			queueId = "zdyfynewJCEBjcbjqueue";
		}
		String wechatCode = jsonData.getString("phoneNum");
		if (StringUtils.isBlank(queueId) && StringUtils.isBlank(wechatCode)) {
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,
					"入参节点错误，队列id和wechatCode不能都为空！"));
		}

		String channel = jsonData.getString("channel");
		if (null == channel || !PropertiesUtils.getProperty("channel").equals(channel)) {
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "channel传入为空或者传入值不正确!");
		}
		Map<String, Object> servParamMap = jsonData;

		String authorName = (String) jsonData.get("patientName");// 登录账号医生姓名
		String deptId = "";
		String tenantId = "";

		/* 微信id获取 */  //不区分 暂时不用
		String code = jsonData.getString("code");// 微信code
		String openId = jsonData.getString("openId");// 微信id
		if(Constants.EVLATATION_QUEUE_ID_2.equals(queueId)){//乐慧公众号 月度评估
		 	String appid_lh = PropertiesUtils.getProperty("appid_lh");
			String secret_lh = PropertiesUtils.getProperty("secret_lh");
	        Map<String, Object> param = new HashMap<String, Object>();
			param.put("appId", appid_lh);
			param.put("secret", secret_lh);
			param.put("code", code);
			if (StringUtils.isBlank(openId)	) {
				if (!StringUtils.isBlank(code)) {
					 Map<String,Object> map = weChatUserService.getOpenId(param);
				        openId = (String)map.get("openId");
				}
			}

//		}else if(Constants.EVLATATION_QUEUE_ID_1.equals(queueId)){//
		}else {//
			/*if (StringUtils.isBlank(openId)) {
				if (StringUtils.isBlank(code)) {
					openId = ToolUtils.getOpenId(code);
				}
			}*/
			String appid_ebsf = PropertiesUtils.getProperty("appid_ebsf");
			String secret_ebsf = PropertiesUtils.getProperty("secret_ebsf");
	        Map<String, Object> param = new HashMap<String, Object>();
			param.put("appId", appid_ebsf);
			param.put("secret", secret_ebsf);
			param.put("code", code);
			if (StringUtils.isBlank(openId)) {
				if (!StringUtils.isBlank(code)) {
					 Map<String,Object> map = weChatUserService.getOpenId(param);
				        openId = (String)map.get("openId");
				}
			}

			String redisKey ="";
			//没有传队列和渠道 默认是儿保随访公众号进来
			if(!StringUtils.isEmpty(wechatCode) && Constants.WECHAT_CHANNEL_EB.equals(wechatCode)){
				redisKey = Constants.ACCESS_TOKEN_EBSF;
				wechatCode = Constants.WECHAT_CHANNEL_EB;
				String token = weChatUserService.getAccessToken(appid_ebsf,secret_ebsf,redisKey);

				if(StringUtils.isBlank(token)){
					logger.error("[月度评估-儿保公众号]获取token失败");
					throw new AppException(ErrorCode.EXCEPTION_WECHAT_SYSTEM_ERROR,"系统繁忙，请稍后重试");
				}

				param = new HashMap<String, Object>();
				param.put("appId", appid_ebsf);
				param.put("secret", secret_ebsf);
				param.put("redisKey", redisKey);
				Map<String,Object> wechatMap = weChatUserService.getUserInfoByToken(token,openId,param);
				Object groupId = wechatMap.get("groupId");

				param.clear();
				if(null == groupId || 0 == Integer.parseInt(groupId.toString())){
					groupId= Constants.DEFAULT_GROUP_EBSF;
				}
				param.put("groupId",groupId);
				param.put("queueUsertype",Constants.QUEUE_USER_TYPE_BABY);
				param.put("optionStatus",Constants.DEPARTMENT_DEFAULT_QUEUE_STATUS);
				param.put("wechatCode", wechatCode);

				Map<String,Object> map = confCacheDao.selectDeptAndQueueIdByCode(param);
				if(null == map || org.springframework.util.StringUtils.isEmpty(map.get("deptId")) || org.springframework.util.StringUtils.isEmpty(map.get("queueId")) ){
					throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_QRCODE_INVALID, "无效二维码渠道"));
				}
				queueId = (String)map.get("queueId");
				deptId = (String)map.get("deptId");
				tenantId =  (String)map.get("tenantId");

				if(StringUtils.isEmpty(queueId)){
					throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_QRCODE_INVALID, "无效二维码渠道"));
				}
			}
		}

		// 查询用户租户id和科室id
		if (!StringUtils.isBlank(queueId)) {
			Map<String, Object> Map = new HashMap<String, Object>();
			Map.put("id", queueId);
			FollowQueue queue = followQueueService.getQueueDetailByQueueId(Map);
			if(null == queue){
				throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_QUEUE_NOT_EXIST,"队列信息不存在");
			}
			deptId = queue.getDeptId();
			tenantId = queue.getTenantId();
		}

		String opCode = jsonData.getString("opCode");
		String opType = jsonData.getString("opType");
		if (StringUtils.isBlank(opCode)) {
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，操作编码为空！"));
		}
		if (StringUtils.isBlank(opType)) {
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，操作类型为空！"));
		}
		if (StringUtils.isBlank(jsonData.getString("opNote"))) {
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，操作备注为空！"));
		}
		String userType = jsonData.getString("userType");
		if (StringUtils.isBlank(userType)) {
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，患者类型为空！"));
		}
		// 来源渠道，入参若无，则默认微信公众号
        String sourceType = jsonData.getString("sourceType");
        if (StringUtils.isBlank(sourceType)) {
            sourceType = Constants.PATIENT_SOURCE_TYPE_WECHAT_OFFICIAL_ACCOUNT;
        }

		// 入参中没有，从问卷答案中获取
		Map<String, Object> quesMap = (JSONObject) jsonData.getJSONObject("questiones");

		String phoneNum = jsonData.getString("phoneNum");
		if (StringUtils.isBlank(phoneNum)) {
			if (null != quesMap && 0 != quesMap.size()) {
				phoneNum = (String) quesMap.get(Constants.QUESTION_ID_FOR_PHONENO);
				if (StringUtils.isBlank(phoneNum)) {
					throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "手机号码不能为空！"));
				}
			}
		}
		phoneNum = phoneNum.trim();
		String patientName = jsonData.getString("patientName");
		if (StringUtils.isBlank(patientName)) {
			if (null != quesMap && 0 != quesMap.size()) {
				patientName = (String) quesMap.get(Constants.QUESTION_ID_FOR_PATIENTNAME);
				if (StringUtils.isBlank(patientName)) {
					throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "患者姓名不能为空！"));
				}
			}
		}
		patientName = patientName.trim();
		String gender = jsonData.getString("gender");
		if (StringUtils.isBlank(gender)) {
			if (null != quesMap && 0 != quesMap.size()) {
				gender = (String) quesMap.get(Constants.QUESTION_ID_FOR_GENDER);
				if (StringUtils.isBlank(gender)) {
					throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "性别不能为空！"));
				}
			}
		}else{
			if (null != quesMap && 0 != quesMap.size()) {
				String gendertemp = (String) quesMap.get(Constants.QUESTION_ID_FOR_GENDER);
				if (!StringUtils.isBlank(gendertemp)) {
					if (Constants.GENDER_FOR_MALE.equals(gender)) {
						jsonData.getJSONObject("questiones").put(Constants.QUESTION_ID_FOR_GENDER,Constants.GENDER_ALIAS_FOR_MALE);
					} else if (Constants.GENDER_FOR_FEMALE.equals(gender)) {
						jsonData.getJSONObject("questiones").put(Constants.QUESTION_ID_FOR_GENDER,Constants.GENDER_ALIAS_FOR_FEMALE);
					}
				}
			}
		}
		gender = gender.trim();
		// 转换性别
		if (Constants.GENDER_ALIAS_FOR_MALE.equals(gender)) {
			gender = Constants.GENDER_FOR_MALE;
		} else if (Constants.GENDER_ALIAS_FOR_FEMALE.equals(gender)) {
			gender = Constants.GENDER_FOR_FEMALE;
		} else if (!Constants.GENDER_FOR_MALE.equals(gender) && !Constants.GENDER_FOR_FEMALE.equals(gender)) {
			gender = Constants.GENDER_FOR_MALE;
		}

		String birthday = jsonData.getString("birthday");
		if (StringUtils.isBlank(birthday)) {
			if (null != quesMap && 0 != quesMap.size()) {
				birthday = (String) quesMap.get(Constants.QUESTION_ID_FOR_BIRTHDAY);
				if (StringUtils.isBlank(birthday)) {
					throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "出生日期不能为空！"));
				}
			}
		}

		String expectedDay = jsonData.getString("expectedDay");

		// 校验预产期是否传入
		Patient pt = new Patient();
		pt.setPregnancyDay(jsonData.getIntValue("pregnancyWeek"));
		if (0 == pt.getPregnancyDay() && !StringUtils.isBlank(expectedDay)) {
			// 根据生日和预产期计算孕周
			int pregnancyDay = ToolUtils.calPrenDayByBirthAndExpect(birthday, expectedDay);
			pt.setPregnancyDay(pregnancyDay);
		}

		if (StringUtils.isBlank(expectedDay)) {
			int day = Constants.PATIENT_NORMAL_PREGNANT_DAY - pt.getPregnancyDay();
			expectedDay = DateUtil.calcDay2(birthday, Constants.PLUS_CHAR, day);

			if(null != jsonData.getJSONObject("questiones")){
				jsonData.getJSONObject("questiones").put(Constants.QUESTION_ID_FOR_EXPECTEDDAY, expectedDay);
			}
		}

		pt.setUserName(patientName);
		pt.setPhoneNo(phoneNum);
		pt.setFirstName(patientName.substring(0, 1));
		pt.setCreateTime(currTime);
		pt.setUpdateTime(currTime);
		pt.setCreateAuthor("微信端");
		pt.setBirthday(birthday);
		pt.setExpectedDay(expectedDay);
		pt.setGender(gender);
		pt.setUserType(userType);
		pt.setSourceType(sourceType);
		pt.setWechat_id(openId);

		servParamMap.put("sourceType", sourceType);
		servParamMap.put("patient", pt);
		servParamMap.put("authorName", authorName);
		servParamMap.put("deptId", deptId);
		servParamMap.put("queueId", queueId);
		servParamMap.put("updateTime", currTime);
		servParamMap.put("authorId", "微信端");
		servParamMap.put("updateAccept", updateAccept);
		servParamMap.put("tenantId", tenantId);
		servParamMap.put("opCode", opCode);
		servParamMap.put("opNote", jsonData.getString("opNote"));
		servParamMap.put("opType", opType);
		servParamMap.put("contentData", jsonData.getJSONObject("questiones"));
		logger.info("微信月度评估：" + servParamMap.toString());

		JSONArray answers = jsonData.getJSONArray("answers");
		if(null != answers){
			servParamMap.put("answers",answers);
		}

		Map<String, Object> userMap = patientqueryCardService.registerMonthCommit(servParamMap);
		logger.info("chucan======" + userMap.toString());
		/*if (CollectionUtils.isEmpty(userMap)) {
			userMap = patientSerivce.registerPatient(servParamMap);
		}*/
		return new ResultModel<Map<String, Object>>(userMap);
	}

	// 查询当前用户当月评估记录
	@ResponseBody
	@RequestMapping("/queryAssessmentRecords")
	public ResultModel<List<Map<String, Object>>> queryAssessmentRecords(@RequestBody String arg) throws Exception {
		logger.warn("in queryAssessmentRecords----arg==" + arg);

		JSONObject jsonArg = null;
		try {
			jsonArg = JSON.parseObject(arg);
		} catch (Exception ex) {
			ex.printStackTrace();
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR, "入参格式错误，非json格式！"));
		}

		JSONObject jsonData = jsonArg.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD);
		if (null == jsonData) {
			// 前台必须传data节点，否则报错返回
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！"));
		}

		String channel = jsonData.getString("channel");
		if (null == channel || !PropertiesUtils.getProperty("channel").equals(channel)) {
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "channel传入为空或者传入值不正确!");
		}
		String queueId = jsonData.getString("queueId");
		if (null == queueId || "".equals(queueId)) {
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "队列传入为空或者传入值不正确!");
		}

		String phoneNo = jsonData.getString("phoneNo");
		String userName = jsonData.getString("userName");

		String opCode = jsonData.getString("opCode");
		if (StringUtils.isBlank(opCode)) {
			opCode = "1110";
		}
		// 排序字段
		String fieldName = jsonData.getString("fieldName");
		if (StringUtils.isBlank(fieldName)) {
			fieldName = "op_time";
		}
		// 升序还是降序
		String order = jsonData.getString("order");
		if (StringUtils.isBlank(order)) {
			order = "desc";
		}
		List<Map<String, Object>> lists = new ArrayList<Map<String, Object>>();
		String tenantId = "";
		// 查询用户租户id和科室id
		if (!StringUtils.isBlank(queueId)) {
			Map<String, Object> Map = new HashMap<String, Object>();
			Map.put("id", queueId);
			FollowQueue queue = followQueueService.getQueueDetailByQueueId(Map);
			tenantId = queue.getTenantId();
		}
		HashMap<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("tenantId", tenantId);
		paramMap.put("phoneNo", phoneNo);
		paramMap.put("userName", userName);
		paramMap.put("page", jsonData.getString("page"));
		paramMap.put("rows", jsonData.getString("rows"));
		paramMap.put("opCode", opCode);
		paramMap.put("fieldName", fieldName);
		paramMap.put("order", order);
		paramMap.put("queueId", queueId);

		lists = patientqueryCardService.selectTotle(paramMap);

		return new ResultModel<List<Map<String, Object>>>(lists);
	}

	// 根据科研编号查询用户
	@ResponseBody
	@RequestMapping("/queryUserByScientific")
	public ResultModel<Map<String, Object>> queryUserByScientific(@RequestBody String arg) throws Exception {
		logger.warn("in queryUserByScientific----arg==" + arg);

		JSONObject jsonArg = null;
		try {
			jsonArg = JSON.parseObject(arg);
		} catch (Exception ex) {
			ex.printStackTrace();
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR, "入参格式错误，非json格式！"));
		}

		JSONObject jsonData = jsonArg.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD);
		if (null == jsonData) {
			// 前台必须传data节点，否则报错返回
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！"));
		}

		String channel = jsonData.getString("channel");
		if (null == channel || !PropertiesUtils.getProperty("channel").equals(channel)) {
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "channel传入为空或者传入值不正确!");
		}
		String queueId = jsonData.getString("queueId");
		if (null == queueId || "".equals(queueId)) {
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "队列传入为空或者传入值不正确!");
		}

		String phoneNo = jsonData.getString("phoneNo");
		String userName = jsonData.getString("userName");
		String ScientificId= jsonData.getString("ScientificId");//科研编号
		if (null == ScientificId || "".equals(ScientificId)) {
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "科研编号不能为空!");
		}
		Map<String, Object> mapOut = new HashMap<String, Object>();
		String tenantId = "";
		// 查询用户租户id和科室id
		if (!StringUtils.isBlank(queueId)) {
			Map<String, Object> Map = new HashMap<String, Object>();
			Map.put("id", queueId);
			FollowQueue queue = followQueueService.getQueueDetailByQueueId(Map);
			tenantId = queue.getTenantId();
		}
		HashMap<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("tenantId", tenantId);
		paramMap.put("phoneNo", phoneNo);
		paramMap.put("userName", userName);
		paramMap.put("ScientificId", ScientificId);
		paramMap.put("queueId", queueId);
		mapOut = patientqueryCardService.queryUserByScientific(paramMap);
		return new ResultModel<Map<String, Object>>(mapOut);
	}
}
